package cn.xyt.service;

import java.util.Map;

import javax.annotation.Resource;

import org.springframework.stereotype.Service;

import cn.tom.kit.IoBuffer;
import cn.tom.protocol.http.HttpMessage;
import cn.xyt.dto.Form;
import cn.xyt.dto.Header;
import cn.xyt.dto.Message;
import cn.xyt.dto.SystemProperty;
import cn.xyt.util.DeviceCache;
import cn.xyt.util.DeviceCache.InetChannel;
import cn.xyt.util.HttpUtil;
import cn.xyt.util.PullSession;
import cn.xyt.util.WebRequestCache;
/**
 *	http://cdz.51xytu.com:7073/sendcmd?cmds=A7&deviceid=1088627070&code=1,1
 *  @author tomsun
 *  
 */
@Service
public class CmdService extends BaseService{
	
	@Resource
	SystemProperty systemProperty;

	
	public Message getDefaultMsg(Form form){
		Header header = new Header();
		String deviceid0 =  form.getDeviceid().substring(1);
		int a =  Integer.parseInt(deviceid0.substring(0, 2));
		int b =  Integer.parseInt(deviceid0.substring(2, 4));
		int c =  Integer.parseInt(deviceid0.substring(4, 6));
		int d =  Integer.parseInt(deviceid0.substring(6, 8)) | 0x80 ;
		int e =  Integer.parseInt(deviceid0.substring(8, 10));
		header.setDeviceid(new byte[]{(byte)a,(byte)b,(byte)c,(byte)d,(byte)e});
		Message msg = new Message(header);
		return msg;
	}
	
	/**
	 * 设置短信报警发送选择命令
	 * http://cdz.51xytu.com:7073/sendcmd?cmds=A7&deviceid=1088627070&code=1,1,300 {充电口,序号,金额}
	 * @param form
	 * @return
	 */
	public Map<String, Object> cmd_A7(Form form){
		Message msg = getDefaultMsg(form);
		
		String[] code = form.getCode().split(",");
		IoBuffer buf = IoBuffer.allocate(20);
		buf.writeByte(0xAA);
		buf.writeByte(Integer.parseInt(code[0]));// 充电口
		buf.writeByte(0);//  
		buf.writeByte(0xA7);//  
		
		buf.writeByte(8+3+3);// len
		long serial = Long.parseLong(code[1]);//  序列号 
		buf.writeLong(serial);
		buf.writeByte(0);
		buf.writeShort(Short.parseShort(code[2]));
		buf.writeByte(0);
		buf.writeShort(Short.parseShort(code[2]));
		buf.writeByte(1);// bodycheck
		//8e 88 00 58 3e c6 46 00 ab 00 00 aa 
		//AA 01 00 A7 
		//0E 
		//00 00 00 00 00 00 00 00 
		//00 01 2C
		//01 F6 0B
		buf.flip();
		byte[] body = buf.readBytes(buf.limit());
		msg.setBody(body);
		sendMessageAsync(msg, form);
		return form.getResp();
	}
	
	
	/**
	 * 取消充电
	 * @param form
	 * @return
	 */
	public Map<String, Object> cmd_D6(Form form){
		Message msg = getDefaultMsg(form);
		
		String code = form.getCode();
		IoBuffer buf = IoBuffer.allocate(20);
		buf.writeByte(0xAA);
		buf.writeByte(Integer.parseInt(code));// 充电口
		buf.writeByte(0);//  
		buf.writeByte(0xD6);//  
		
		buf.writeByte(1);// len
		buf.writeByte(1);//  
		buf.writeByte(1);//  
		buf.flip();
		byte[] body = buf.readBytes(buf.limit());
		msg.setBody(body);
		sendMessageAsync(msg, form);
		return form.getResp();
	}
	
	
	/**
	 * 取消充电
	 * @param form
	 *  code 单价 5
	 * @return
	 */
	public Map<String, Object> cmd_A5(Form form){
		Message msg = getDefaultMsg(form);
		
		String code = form.getCode();
		IoBuffer buf = IoBuffer.allocate(20);
		buf.writeByte(0xAA);
		buf.writeByte(1);// 充电口
		buf.writeByte(0);//  
		buf.writeByte(Integer.parseInt(form.getCmd(), 16));//  
		//AA 01 00 A5 0A 
		// 14 00 3C 64 14 00 3C 14 00 3C xor
		
		 //00 05 3c 64 00 05 3c 00 05 65 d4 8f  
		buf.writeByte(10);// len
		short price = Short.parseShort(code);
		buf.writeByte(price); 
		buf.writeShort((short)60);
		buf.writeByte(100);
		buf.writeByte(price); 
		buf.writeShort((short)60);
		buf.writeByte(price); 
		buf.writeShort((short)60);
		buf.writeByte(1).flip();
		byte[] body = buf.readBytes(buf.limit());
		msg.setBody(body);
		sendMessageAsync(msg, form);
		return form.getResp();
	}
	
	
	
	/************** 新增协议位置*******************/
	/**
	 * 异步回复
	 * @param msg
	 */
	public void resp_comm_async(Message msg){
		byte[] body = msg.getBody();
		int state = body[5];
		String res = FAILD;
		if(state == 1){
			res = SUCCESS;
		}

		String key = ""+msg.getHeader().getDeviceidByByte();
		PullSession ps = WebRequestCache.get(key);  // 超期后,已经remove掉, 返回form可能为 null

		if(ps !=null){
			HttpMessage httpmsg = ps.getPullMessage();
			httpmsg.setJsonBody(HttpUtil.serialize(correct(res)));
			httpmsg.setStatus("200");  
			ps.getSession().write(httpmsg);
			WebRequestCache.remove(key);
		}
	};
	
	
	
	/**
	 * 异步发送
	 * @param message
	 * @param form
	 */
	private String sendMessageAsync(final Message message, final Form form) {
		InetChannel inet = DeviceCache.get(form.getDeviceid());
		if(inet == null) {
			form.setResp(error("设备不在线"));
			logger.info("设备不在线 id={}", form.getDeviceid());
			return null;
		}
		inet.channel.writeAndFlush(message);
		// 优先序号  后来 
		String webcashkey = form.getDeviceid();
		
		form.setResp(correct("发送命令中", webcashkey));
		long deviceid = message.getHeader().getDeviceidByByte();
		logger.info("sendMessage already, cmd:{} code:{}, id:{}",  form.getCmd(),form.getCode() , deviceid);
		return webcashkey;
	}
	
	
	public static void main(String[] args) {
		short a = (short) (System.currentTimeMillis()/10000000);
		System.out.println(System.currentTimeMillis());
		System.out.println(Short.MAX_VALUE);
		System.out.println(a);
	}
}
